<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace Haozing\FastCore\Abstract;

use Haozing\FastCore\Interfaces\AppsConfigInterface;
use Haozing\FastCore\Traits\ControllerTrait;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\EventDispatcher\EventDispatcherInterface;

abstract class AbstractController
{
    use ControllerTrait;
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    private EventDispatcherInterface $eventDispatcher;

    #[Inject]
    protected LoggerFactory $logger;

    /**
     * 获取模块的配置文件
     * @param string $baseValue tab基础值
     * @param string $key 配置项的key
     * @param array $where 查询条件
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getModuleConfig(string $baseValue = '',string $key = '', array $where = []): array
    {
        $class = $this->getModuleName();
        if (!empty($class)) {
            return $this->container->get(AppsConfigInterface::class)->getAppConfig($class,$baseValue,$key,$where);
        }
        return [];
    }

    /**
     * 获取租户公共的配置
     */
    public function getTenantConfig(string $baseValue = '',string $key = '', array $where = []): array
    {
        //从上下文中获取租户id
        $where['tenant_id'] = $this->getTenantId();
        return $this->container->get(AppsConfigInterface::class)->getAppConfig("Base",$baseValue,$key,$where);
    }
    /**
     * 获取租户公共的配置
     */
    public function getTenantModuleConfig(string $baseValue = '',string $key = '', array $where = []): array
    {
        $class = $this->getModuleName();
        if (!empty($class)) {
            //从上下文中获取租户id
            $where['tenant_id'] = $this->getTenantId();
            return $this->container->get(AppsConfigInterface::class)->getAppConfig($class,$baseValue,$key,$where);
        }
        return [];
    }
    /**
     * 获取模块的名称
     */
    public function getModuleName(): string
    {
        $class = get_class($this);
        $class = explode('\\', $class);
        return $class[1] ?? '';
    }

    /**
     * 获取租户id
     */
    public function getTenantId(): int
    {
        return $this->request->getAttribute('pp-tenant-code',1);
    }
}
